package com.ahdms.es.gm.asn1.generic;

import org.bouncycastle.asn1.*;
import org.bouncycastle.asn1.ocsp.CertID;
import org.bouncycastle.asn1.x509.CRLReason;

import java.util.Enumeration;

public class CertStatus extends ASN1Object {

    private CertID certId;
    private ASN1GeneralizedTime beforeTime;
    private ASN1GeneralizedTime endTime;
    private ASN1Integer status;
    private ASN1GeneralizedTime statusTime;
    private CRLReason statusReasonCode;

    private CertStatus(ASN1Sequence seq) {
        Enumeration en = seq.getObjects();
        certId = CertID.getInstance(en.nextElement());
        beforeTime = ASN1GeneralizedTime.getInstance(en.nextElement());
        endTime = ASN1GeneralizedTime.getInstance(en.nextElement());
        status = ASN1Integer.getInstance(en.nextElement());
        statusTime = ASN1GeneralizedTime.getInstance(en.nextElement());
        if (en.hasMoreElements()) {
            statusReasonCode = CRLReason.getInstance(en.nextElement());
        }
    }

    public static CertStatus getInstance(
            ASN1TaggedObject tagObj,
            boolean explicit) {
        return CertStatus.getInstance(ASN1TaggedObject.getInstance(tagObj, true));
    }

    public static CertStatus getInstance(Object o) {
        if (o instanceof CertStatus) {
            return (CertStatus) o;
        } else if (o != null) {
            return new CertStatus(ASN1Sequence.getInstance(o));
        }

        return null;
    }

    public CertID getCertId() {
        return certId;
    }

    public ASN1GeneralizedTime getBeforeTime() {
        return beforeTime;
    }

    public ASN1GeneralizedTime getEndTime() {
        return endTime;
    }

    public ASN1Integer getStatus() {
        return status;
    }

    public ASN1GeneralizedTime getStatusTime() {
        return statusTime;
    }

    public CRLReason getStatusReasonCode() {
        return statusReasonCode;
    }

    public CertStatus(CertID certId, ASN1GeneralizedTime beforeTime, ASN1GeneralizedTime endTime, ASN1Integer status,
                      ASN1GeneralizedTime statusTime, CRLReason statusReasonCode) {
        this.certId = certId;
        this.beforeTime = beforeTime;
        this.endTime = endTime;
        this.status = status;
        this.statusTime = statusTime;
        if (null != statusReasonCode) {
            this.statusReasonCode = statusReasonCode;
        }
    }

    public ASN1Primitive toASN1Primitive() {
        ASN1EncodableVector seq = new ASN1EncodableVector();
        seq.add(certId);
        seq.add(beforeTime);
        seq.add(endTime);
        seq.add(status);
        seq.add(statusTime);
        if (null != statusReasonCode) {
            seq.add(statusReasonCode);
        }

        return new DERSequence(seq);
    }

}

